package com.bbs.service;

import cn.hutool.core.collection.ListUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bbs.common.dto.ForumListDTO;
import com.bbs.common.entity.Forum;
import com.bbs.common.entity.User;
import com.bbs.common.exception.CommonException;
import com.bbs.common.mapper.ForumMapper;
import com.bbs.common.mapper.UserMapper;
import com.bbs.common.utils.SessionManager;
import com.bbs.common.vo.ForumListVo;
import com.bbs.common.vo.PageVo;
import com.bbs.dto.ForumSaveDTO;
import com.bbs.vo.ForumDetailVo;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Log4j2
public class ForumService {

    @Autowired
    private ForumMapper forumMapper;

    @Autowired
    private UserMapper userMapper;

    // 帖子发布
    public void save(ForumSaveDTO saveDTO) {
        int userId = SessionManager.getUser().getId();
        log.info("帖子发布，params:{}", JSONObject.toJSONString(saveDTO)); // 打印参数
        Forum forum = new Forum();
        BeanUtils.copyProperties(saveDTO, forum); // 复制属性
        forum.setUserId(userId);
        forum.setDeleteFlag(0);
        forum.setCreateTime(LocalDateTime.now());
        forum.setUpdateTime(LocalDateTime.now());
        forumMapper.insert(forum);
    }

    // 查询全部
    public List<List<ForumListVo>> list(ForumListDTO listDTO) {
        List<ForumListVo> list = forumMapper.list(listDTO);
        return ListUtil.partition(list, 4); // 一行四个
    }

    /**
     * 我的发布
     **/
    public PageVo<Forum> myList(ForumListDTO listDTO) {
        Page<Forum> queryPage = new Page<>(listDTO.getCurrentPage(), listDTO.getPageSize());
        QueryWrapper<Forum> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Forum::getUserId, SessionManager.getUser().getId()).eq(Forum::getDeleteFlag, 0);
        if (StringUtils.hasText(listDTO.getTitle())) { // 没有搜索条件就默认全查，有就提供模糊搜索
            queryWrapper.lambda().like(Forum::getTitle, listDTO.getTitle());
        }
        queryWrapper.lambda().orderByDesc(Forum::getCreateTime); // 按时间倒序呈现
        IPage<Forum> page = forumMapper.selectPage(queryPage, queryWrapper);
        return new PageVo<>(page);
    }

//    // 查询（分割）
//    public List<List<ForumListVo>> all() {
//        List<ForumListVo> list = forumMapper.all();
//        return ListUtil.partition(list, 4); // 一行四个
//    }

//    // 查看个人发布 // 改动后已合并
//    public List<Forum> my() {
//        int userId = SessionManager.getUser().getId();
//        QueryWrapper<Forum> queryWrapper = new QueryWrapper<>();
//        // 挑选userId符合的，筛选未被删除的，降序排序
//        // queryWrapper.lambda()：创建一个 Lambda 查询包装器，允许你以类型安全的方式构建查询条件
//        // :: 是 Java 8 引入的方法引用（Method Reference）语法，用于引用类中的方法
//        queryWrapper.lambda().eq(Forum::getUserId, userId).eq(Forum::getDeleteFlag, 0).orderByDesc(Forum::getCreateTime);
//        return forumMapper.selectList(queryWrapper);
//    }

    // 根据id去删除
    public void delete(int id) {
        Forum forum = forumMapper.selectById(id);
        if(null == forum) {
            throw new CommonException("信息未找到");
        }
        forum.setDeleteFlag(1);
        forum.setUpdateTime(LocalDateTime.now());
        forumMapper.updateById(forum);
    }

    public ForumDetailVo detail(int id) {
        Forum forum = forumMapper.selectById(id);
        if (forum.getDeleteFlag() == 1) {
            throw new CommonException("帖子已被删除");
        }
        ForumDetailVo vo = new ForumDetailVo();
        BeanUtils.copyProperties(forum, vo);
        User user = userMapper.selectById(forum.getUserId());
        vo.setUserName(user.getName());

        int userId = SessionManager.getUser().getId();
        if (userId != forum.getUserId()) {
//            forum.setViews(forum.getViews() + 1);
            forumMapper.updateById(forum);
        }

//        // 是否收藏
//        QueryWrapper<ForumCollect> queryWrapper = new QueryWrapper<>();
//        queryWrapper.lambda().eq(ForumCollect::getForumId, id).eq(ForumCollect::getUserId, userId);
//        if (forumCollectMapper.exists(queryWrapper)) {
//            vo.setCollectFlag(true);
//        }

        return vo;
    }
}
